package cool.taomu.toolkit.cacheable.provider

import java.util.Map
import javax.inject.Provider
import redis.clients.jedis.JedisPool
import redis.clients.jedis.JedisPoolConfig

class RedisProvider implements Provider<JedisPool> {

    Map<String, Object> config

    new(Map<String, Object> config) {
        this.config = config
    }

    override get() {
        if ((config.get("type") as String).equalsIgnoreCase("redis")) {
            var jedisPoolConfig = new JedisPoolConfig();
            // this.configure(jedisPoolConfig);
            var password = this.config.containsKey("password") ? this.config.get("password") as String : null;
            var user = this.config.containsKey("username") ? this.config.get("username") as String : null;
            var timeout = this.config.containsKey("timeout") ? this.config.get("timeout") as Integer : 6000
            var host = this.config.containsKey("host") ? this.config.get("host") as String : "127.0.0.1"
            var port = this.config.containsKey("port") ? this.config.get("port") as Integer : 6735
            // LOG.info("创建Redis连接: {}:{}", host, port);
            var JedisPool pool;
            if (user === null) {
                if (password === null) {
                    pool = new JedisPool(jedisPoolConfig, host, port);
                } else {
                    pool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
                }
            } else if (user !== null && password !== null) {
                pool = new JedisPool(jedisPoolConfig, host, port, timeout, user, password);
            }
            return pool;
        }
    }
}
